package com.yin.myproject.zk.base;

import com.yin.myproject.zk.client.ZkClient;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

/**
 * Created by Eason on 2017/8/4.
 */
public class NodeSample {

    public static void main(String[] args) throws Exception {
        CuratorFramework zkClient = ZkClient.getZkClient();
        zkClient.start();
//        String path = "/task11";
//        //新建节点
////        new NodeSample().createNode(zkClient, path);
//        //查询节点
////        new NodeSample().getNode(zkClient, path);
//        List<String> strings = zkClient.getChildren().forPath("/");
//        for (String str : strings) {
//            System.out.println(str);
//        }
//        //删除节点
//        zkClient.delete().forPath(path);

//        testEphemeral();
        zkClient.getChildren().forPath("/");
    }

    /**
     * 临时节点测试
     *
     * @throws Exception
     */
    public static void testEphemeral() throws Exception {
        CuratorFramework newZkClient = ZkClient.getNewZkClient();
        newZkClient.start();
        String path = "/taskWatch";
        newZkClient.create().withMode(CreateMode.EPHEMERAL).forPath(path);
        newZkClient.setData().forPath(path, "1233".getBytes());
        newZkClient.getData().forPath(path);
        CuratorFramework zkClient = ZkClient.getZkClient();
        zkClient.start();
        zkClient.getData().forPath(path);
        newZkClient.close();
        Stat stat = zkClient.checkExists().forPath(path);
        System.out.println(stat == null);
    }

    /**
     * 创建节点
     *
     * @param zkClient
     */
    public void createNode(CuratorFramework zkClient, String path) {
        try {
            path = zkClient.create().forPath(path);
            System.out.println(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取节点数据
     *
     * @param zkClient
     * @param path
     * @throws Exception
     */
    public void getNode(CuratorFramework zkClient, String path) throws Exception {
        byte[] bytes = zkClient.getData().forPath(path);
        String s = new String(bytes);
    }
}
